<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . "/controller/ctlAbstract.php";

require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUser.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busAddress.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busLocation.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busCategory.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busQuestion.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busResource.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busProvider.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busItem.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/user.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/address.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/location.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/provider.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/item.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/resource.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/simpleImage.php';

/**
 * This is the class handle the registration of new users
 */
class InputController extends AbstractController {
	/**
	 * This template variable will hold the 'view' portion of our MVC for this
	 * controller
	 */
	private $_userBus;
	private $_addressBus;
	private $_locationBus;
	private $_categoryBus;
	private $_providerBus;
	private $_itemBus;
	private $_questionBus;
	private $_resourceBus;
	/**
	 *
	 * This is the default function that will be called by the router
	 * @param array $getVars GET variables posted to index.php
	 */
	public function main(array $getVars) {
		global $ubi;
		
		$this->_locationBus = new LocationBus();
		$this->_addressBus = new AddressBus();
		$this->_userBus = new UserBus();
		$this->_categoryBus = new CategoryBus();
		$this->_providerBus = new ProviderBus();
		$this->_questionBus = new QuestionBus();
		$this->_resourceBus = new ResourceBus();
		$this->_itemBus = new ItemBus();
		
		if ($getVars['action'] == 'inputProvider') {			
			$addressModel = new AddressModel();			
			$addressModel->setDistrict($this->_locationBus->getLocationFromID($_POST['selDistrict']));
			$addressModel->setNumber($_POST['txtNumber']);
			$addressModel->setStreet($_POST['txtStreet']);
			$addressModel->setWard($this->_locationBus->getLocationFromID($_POST['selWard']));
			$addressModel->setCity($this->_locationBus->getLocationFromID($_POST['selCity']));
			$addressModel->setType($ubi['LOCATION']['PROVIDER']);
			$addressModel->setLocation1($_POST['selCity']);
			$addressModel->setLocation2($_POST['selDistrict']);
			$addressModel->setLocation3($_POST['selWard']);
			$addressModel->setLatitude($_POST['latitude']);
			$addressModel->setLongitude($_POST['longitude']);

			$addressID = $this->_addressBus->addAddress($addressModel);
						
			if ($addressID != 0) {
				if ($_FILES['imgProvider']['error'] > 0) {
						$errList[] = 'Có lỗi khi upload hình';
				} else {
					$addressModel->setAddressID($addressID);
					$fileName = $_FILES['imgProvider']['name'];
					if (file_exists($ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $fileName)) { 
						//file avatar existed
						require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/stringUtil.php';			
						$fileName = StringUtil::changeFileName($fileName);
					}
							
					//create resource model object
					$res = new ResourceModel();
					$res->setResourceName($fileName);
					$res->setShortDescription('provider');
							
					$fileNameResource = $ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $fileName;
					$fileNameThumbnail = $ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['THUMBNAIL_PATH'] . '/' . $fileName;							
					$ck1 = move_uploaded_file($_FILES['imgProvider']['tmp_name'], $fileNameResource);
					$ck2 = copy($fileNameResource, $fileNameThumbnail);
														
					$resID = $this->_resourceBus->addResource($res);										
					
					//add image of provider
					if ($resID != 0) {
						$res->setResourceID($resID);

						$image = new SimpleImage();
						$image->load($fileNameThumbnail);
						$image->resize($ubi['SITE']['WIDTH_THUMBNAIL'], $ubi['SITE']['HEIGHT_THUMBNAIL']);
						$image->save($ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['THUMBNAIL_PATH'] . '/' . $fileName);
								   	
						$image->load($fileNameResource);
						$image->resize($ubi['SITE']['WIDTH_RESOURCE'], $ubi['SITE']['HEIGHT_RESOURCE']);
						$image->save($ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $fileName);
						
						do {
							$mapFileName = "Map" . GeneralFunctions::createRandomCode() . ".jpg";
							$newFileName = $ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $mapFileName;
						} while (file_exists($newFileName));

						$addrStr = $addressModel->getNumber() . ", " . $addressModel->getStreet() . ", " . $addressModel->getDistrict() . ", " . $addressModel->getCity() . ", " . "Vietnam";
						$addrStr = urlencode($addrStr);
//						$urlSite = "http://maps.google.com/maps/api/staticmap?zoom=15&size=317x350&markers=color:blue%7Clabel:S%7C" . $addrStr . "&sensor=true&format=jpg";
//						$urlSite = "http://maps.google.com/maps/api/staticmap?center=" + coords.latitude + "," + coords.longitude + "&zoom=13&size=320x480&maptype=roadmap&key=MyGoogleMapsAPIKey&sensor=true";
						if (!isset($_POST['latitude']) || isset($_POST['longitude'])) {
							$urlSite = "http://maps.google.com/maps/api/staticmap?zoom=15&size=317x350&markers=color:blue%7Clabel:S%7C" . $addrStr . "&sensor=true&format=jpg";
						} else {
							$urlSite = "http://maps.google.com/maps/api/staticmap?center=" . $addressModel->getLatitude() . "," . $addressModel->getLongitude()
								. "&zoom=15&size=317x350&markers=color:blue%7Clabel:S%7C&sensor=true&format=jpg";
						}	
						GeneralFunctions::get_file($urlSite, $newFileName);
						
						$res = new ResourceModel();
						$res->setResourceName($mapFileName);
						$res->setShortDescription('map');
						$mapResID = $this->_resourceBus->addResource($res);
						
						$providerModel = new ProviderModel();
						$providerModel->setAddressID($addressID);
						$providerModel->setCategoryList($_POST['categoryProviderList']);
						$providerModel->setDescription($_POST['txtProviderDes']);
						$providerModel->setProvider($_POST['txtProviderName']);
						$providerModel->setTelephone($_POST['txtTelephone']);
						$providerModel->setUserID($_SESSION['userid']);
						$providerModel->setAnswerList($_POST['answerList']);
						$providerModel->setCellphone($_POST['txtCellphone']);	
						$providerModel->setTelephone($_POST['txtTelephone']);
						$providerModel->setWebsite($_POST['txtWebsite']);
						$providerModel->setEmail($_POST['txtEmail']);						
						$providerModel->setResourceList($resID);
						$providerModel->setUserID($_SESSION['userid']);
						$providerModel->setMapResourceID($mapResID);
												
						$providerID = $this->_providerBus->addProvider($providerModel);
						if ($providerID != 0) {
							$url = 'index.php?view&type=provider&id=' . $providerID;							
							header('Location:' . $url);
						}
					}
				}				
			}
		} else if ($getVars['action'] == 'inputItem') {
			$userid = $_SESSION['userid'];
			if ($userid) {		
				if ($_FILES['imgItem']['error'] > 0) {
					$errList[] = 'Có lỗi khi upload hình';
				} else {
					$fileName = $_FILES['imgItem']['name'];
					if (file_exists($ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $fileName)) { 
						//file avatar existed
						require_once $ubi['SERVER']['SERVER_ROOT'] . "/utility/stringUtil.php";			
						$fileName = StringUtil::changeFileName($fileName);
					}
								
					//create resource model object
					$res = new ResourceModel();
					$res->setResourceName($fileName);
					$res->setShortDescription('item');			
									
					$fileNameResource = $ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $fileName;
					$fileNameThumbnail = $ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['THUMBNAIL_PATH'] . '/' . $fileName;												
					move_uploaded_file($_FILES['imgItem']['tmp_name'], $fileNameResource);
					copy($fileNameResource, $fileNameThumbnail);
							
					$resID = $this->_resourceBus->addResource($res);										
					
					//add image of provider
					if ($resID != 0) {
						$image = new SimpleImage();
						$image->load($fileNameThumbnail);
						$image->resize($ubi['SITE']['WIDTH_THUMBNAIL'], $ubi['SITE']['HEIGHT_THUMBNAIL']);
						$image->save($fileNameThumbnail);
								   	
						$image->load($fileNameResource);
						$image->resize($ubi['SITE']['WIDTH_RESOURCE'], $ubi['SITE']['HEIGHT_RESOURCE']);
						$image->save($fileNameResource);
						
						$res->setResourceID($resID);
						
						$itemModel = new ItemModel();
						$itemModel->setItem($_POST['txtItem']);
						$itemModel->setDescription($_POST['txtItemDes']);
						$itemModel->setUnit($_POST['selUnit']);
						$itemModel->setCategoryList($_POST['categoryItemList']);
						$itemModel->setBeginPrice($_POST['txtPriceFrom']);
						$itemModel->setEndPrice($_POST['txtPriceTo']);
						$itemModel->setResourceList($resID);
						$itemModel->setProviderId($_POST['ckDiaDiem']);
						$itemModel->setAnswerList($_POST['answerList']);
						$itemModel->setStatus(1);				
						$itemModel->setUserId($_SESSION['userid']);
						
						
						$itemID = $this->_itemBus->addItem($itemModel);
												
						if ($itemID != 0) {
							$url = 'index.php?view&type=item&id=' . $itemID;
							header('Location:' . $url);
						}
					}
				}
			}
		} else if ($getVars['action'] == 'getCategoryProviderQuestion') {	
			echo $this->_questionBus->getQuestionProviderListXML($_POST['cat']);
		} else if ($getVars['action'] == 'getCategoryProvider') {
			$parentID = $_POST['parentID'];
			$catList = $this->_categoryBus->getCategoryProviderList($parentID);
						
			$xml = '<categories>';
			
			foreach ($catList as $cat) {				
				$xml .= '<category id="' . $cat->getCategoryID() . '" name="' . $cat->getCategory() . '" />';				 
			}			
			
			$xml .= '</categories>';
			
			echo $xml;			
		} else if ($getVars['action'] == 'getCategoryItem') {
			$parentID = $_POST['parentID'];
			$catList = $this->_categoryBus->getCategoryItemList($parentID);
						
			$xml = '<categories>';
			
			foreach ($catList as $cat) {				
				$xml .= '<category id="' . $cat->getCategoryID() . '" name="' . $cat->getCategory() . '" />';				 
			}			
			
			$xml .= '</categories>';
			
			echo $xml;
		} else if ($getVars['action'] == 'getCategoryItemQuestion') {
			echo $this->_questionBus->getQuestionItemListXML($_POST['cat']);
		} else {
			require_once $ubi['SERVER']['SERVER_ROOT'] .  '/view/viewInput.php';
		}		
	}
}
?>